﻿import React from 'react';
import ReactDOM from 'react-dom';
import mirror, {actions, connect} from 'mirrorx';
import { List, InputItem, WhiteSpace, WingBlank, Button,Checkbox,Picker,Flex,Modal,Badge,DatePicker } from 'antd-mobile';
const ListItem = List.Item;
import { createForm } from 'rc-form';

import { FormattedMessage} from 'react-intl';


class App extends React.Component { 
	constructor(props) {
		super(props);

		this.state={
			errorMap:{},
			autoHideMap:{
				sex:true,
				birthdate:true
			},
			cardTypeId:"SHENFENZHENG",
			info:{},			
		}

		const Lang = window.LangMessage;

		this.keyCodes = [{
			keycode:"name",
			text:Lang.name ||"姓名",
			
		},{
			keycode:"cardType",
			text:Lang.certi_type ||"证件类型",
			type:"select"
		},{
			keycode:"cardNumber",
			text:Lang.certi_no ||"证件号码",
			message:Lang.cert_tip || "请输入合法的证件号码"
		},{
			keycode:"sex",
			text:Lang.gender_text ||"性别",
			type:"select"
		},{
			keycode:"birthdate",
			text:Lang.date_of_birth ||"出生日期",
			type:"date"
		},{
			keycode:"socialSecurity",
			text:'国民健康保険' || Lang.social_insurance ||"社保",
			type:"select"
		}];
	} 

	componentDidMount(){
		this.requestCustomerDetail();
	}

	requestCustomerDetail=()=>{//請求客戶信息
		T.fetch({
			url:'/msg/account/authDetail.json',
			data:{}
			}).then((res)=>{
				console.log(res);
				this.setState({
					info:res.value
				})
			})
	}
	
	onErrorClick=(keyCode)=>{
		const Lang = window.LangMessage;
		const {getFieldError } = this.props.form;
		let msg = getFieldError(keyCode);
		if(keyCode == "cardNumber"){
			msg=[Lang.cert_tip ||"请输入合法的证件号码"]
		}
		if(msg){
			T.showError(msg.join(","),2);
		}	
	}

	validateAction = (callback)=>{
		this.props.form.validateFields((error, values) => {
			var errorMap ={};
			if(values.cardNumber){
				if(!this.checkCardNumber(values.cardNumber)){
					error = error ||{}
					error["cardNumber"] = true;
				}else{
					if(error){
						error["cardNumber"] = false;
					}
					
				}
			}
			if(error){
				for(var key in error){
					errorMap[key] = true;
				}
			}else{
				if(values.cardType == "SHENFENZHENG"){
					values = {...values,...this.getSexAndBirth(values.cardNumber)}					
				}
				for(let key in values){
					if(T.isArray(values[key])){
						values[key] = values[key].toString();
					}
				}
				callback && callback(values);
			}

			setTimeout(()=>{
				this.setState({
					errorMap
				});
			}, 0);
			
			console.log(error, values);			
		});
	}
	
	submitAction=()=>{
		this.validateAction((values)=>{		
			let params = {
				name:values.name,
				gender:values.sex,
				birthday:Date.parse(new Date(values.birthdate)),
				socialSecurity:values.socialSecurity,
				customerId:this.state.info.id,
				certiType:values.cardType,
				certiNo:values.cardNumber
			}
			//console.log(params);
			T.fetch({
				url:'/account/saveCustomer.json',
				data:params
			}).then((res)=>{
				if(res.success){
					T.showSuccess('认证成功');
				}
			})
			
		})
	}

	selectClick = (key,value)=>{
		if(key =="cardType"){
			this.autoHideSexAndBirth(value);
		}
	}

	inputBlur = (key,value)=>{
		if(key =="cardNumber" && value){
			this.checkCardNumber(value)
		}
	}
	checkCardNumber = (value)=>{
		let result = true;
		if(this.state.cardTypeId ==1){
			if(!T.check.idCard(value)){
				result = false;
			}
		}
		if(this.state.cardTypeId ==2){
			if(!/^(?![a-zA-Z]+$)[\da-zA-Z]{6,18}$/i.test(value)){
				result = false
			}
		}

		setTimeout(()=>{
			let errorMap = this.state.errorMap;
			errorMap.cardNumber = !result;
			this.setState({
				errorMap
			});
		}, 0);

		return result;
	}

	autoHideSexAndBirth = (cardTypeId)=>{
		let  autoHideMap = this.state.autoHideMap ||{};
		if(cardTypeId == "SHENFENZHENG"){
			autoHideMap.sex = autoHideMap.birthdate = true;
		}else{
			autoHideMap.sex = autoHideMap.birthdate = false;
		}
		this.setState({
			cardTypeId,
			autoHideMap
		})
	}

	getSexAndBirth = (cardId)=>{
		var birthdate = cardId.substr(6, 8);
		birthdate = this.formatDate(birthdate);
		var sex = cardId.substr(16, 1) % 2 === 1 ? 'MALE' : 'FMAIL';
		return {birthdate,sex}
	}

	formatDate = (dateStr)=> {//20140513 -->   2014-05-13
		if (dateStr.length === 8) {
			var mon = dateStr.substr(4, 1);
			mon = dateStr.substr(4, 2);
			var day = dateStr.substr(6, 1);
			day = dateStr.substr(6, 2);
			return [dateStr.substr(0, 4), mon, day].join("-") + "";
		}

		return dateStr;
	}

	

	getItemDom = (item,index)=>{
		const Lang = window.LangMessage;
		const { getFieldProps } = this.props.form;
		let dom;
		const listMap = {
			cardType : [{label:Lang.ID_card ||"身份證",value:"SHENFENZHENG"},{label:Lang.passport ||"護照",value:"HUZHAO"}],
			sex: [{label:Lang.male || "男",value:"MALE"},{label:Lang.female || "女",value:"FMAIL"}],
			socialSecurity: [{label:Lang.has || "有",value:"YES"},{label:Lang.without ||"無",value:"NO"}],			
		}
		let keyCode = item.keycode;
		let initValue;
		if(keyCode =="name"){
			initValue = "";
			if(this.state.info.name){
				initValue = this.state.info.name;
			}	
		}
		if(keyCode =="cardNumber"){
			initValue = "";
			if(this.state.info.certiNo){
				initValue = this.state.info.certiNo;
			}	
		}
		if(keyCode =="cardType"){
			initValue = "SHENFENZHENG";
			if(this.state.info.certiType){
				initValue = this.state.info.certiType;
			}	
		}
		if(keyCode =="sex"){
			initValue = "MALE";
			if(this.state.info.gender){
				initValue = this.state.info.gender;
			}			
		}
		if(keyCode =="birthdate"){
			initValue = new Date();
			if(this.state.info.birthday){
				initValue = new Date(this.state.info.birthday);
			}	
		}
		if(keyCode =="socialSecurity"){
			initValue = "YES";
			if(this.state.info.socialSecurityr){
				initValue = this.state.info.socialSecurity;
			}	
		}		
		const minDate = new Date('1901-01-01');  
		switch(item.type){
			case "select" :
				dom = <Picker data={listMap[keyCode]} cols={1} 
						{...getFieldProps(keyCode,{
							initialValue:[initValue],
							rules: [{
								required: item.required === undefined ? true:item.required,
								message:item.message || ((Lang.please_select || "请选择") + item.text)
							}],
							onChange:(data)=>{
								this.selectClick(keyCode,data)
							}
						})}
					>
						<ListItem arrow="horizontal">{item.text}</ListItem>
					</Picker>;
			break;
			case "date" :
				dom = <DatePicker 
						mode="date"
						minDate={minDate}
						title={(Lang.please_select || "请选择") + item.text}
						{...getFieldProps(keyCode,{
							initialValue:initValue,
							rules: [{
								required: item.required === undefined ? true:item.required,
								message:item.message || ((Lang.please_select || "请选择") + item.text)
							}],
						})}
					>
						<ListItem arrow="horizontal">{item.text}</ListItem>
					</DatePicker>
		break;
			default:
				let rule = {
					required: item.required === undefined ? true:item.required,
					message:item.message || ((Lang.text_input ||"请输入") + item.text),
					pattern:item.pattern,
					transform:(value)=>{
						return value && value.trim();
					}
				}

				dom = <InputItem  
				{...getFieldProps(keyCode,{
					rules: [rule],
					initialValue:initValue,
				})}				
				onBlur={(value)=>{this.inputBlur(keyCode,value)}}
				type={item.type}
				error ={this.state.errorMap[keyCode]}
				onErrorClick={this.onErrorClick.bind(this,keyCode)}
				clear
				placeholder={(Lang.text_input ||"请输入") + item.text}
				>{item.text}</InputItem>
		}

		return <div key={index}>
				{!this.state.autoHideMap[keyCode] &&
					dom
				}
		    </div>;
	}
	
	render() {
		console.log(this.state)
		
		return (<div className="info-base">
			<WhiteSpace/>
			<List>
			{this.keyCodes.map((item,index)=>
				this.getItemDom(item,index)
			)}
			
		</List>

		<div className="whiteSpace"></div>
			<div className="footer clearfix">
				<Flex>
					<Flex.Item className="tac pt30 pb30 fcw f28 diy_background" onClick={this.submitAction}><FormattedMessage id='submit_cert' defaultMessage='进行认证'/></Flex.Item>
				</Flex>
			</div>
	  	</div>)
	}
}

const AppForm = createForm()(App);

export default AppForm;